import threading
import utils
import json
import os
from login import use_default_login
import tasks
import random
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from openpyxl.utils import get_column_letter
from openpyxl.styles import PatternFill, Border, Side, Alignment

fill_main = PatternFill(
    fill_type='solid', start_color='C6FDCC00', end_color='C6FDCC00')

thin = Side(border_style="thin", color="000000")
border_normal = Border(top=thin, bottom=thin, left=thin, right=thin)
align_header = Alignment(horizontal='center')


def set_columns_width(sheet, columns_width):
    for index, width in enumerate(columns_width):
        sheet.column_dimensions[get_column_letter(index + 1)].width = width


def set_border(rows):
    for row in rows:
        for cell in row:
            cell.border = border_normal


def set_styles(rows, fill=None, alignment=None):
    for row in rows:
        for cell in row:
            if fill:
                cell.fill = fill
            if alignment:
                cell.alignment = alignment


class WeChatInfrastructureEditor(utils.WeChatClient):
    def debug_log(self, err, gh_nickname=None, gh_id=None):
        utils.log_error(self.log_line(err, gh_nickname, gh_id))
        print(err)

    def material_management_info(self, cookies):
        resp = self.session.get('{}/cgi-bin/appmsg?begin=0&count=10&type=10&action=list_card&token={}&'
                                'lang=zh_CN&f=json&ajax=1'.format(self.url, self.token), verify=False)
        try:
            data = resp.json()
            self.driver.maximize_window()
            self.driver.implicitly_wait(20)
            appmsgid = data["app_msg_info"]["item"][0]["app_id"]
            self.driver.get("{0}/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=10"
                            "&appmsgid={1}&isMul=1&token={2}&lang=zh_CN".format(self.url, appmsgid, self.token))
            for key, value in cookies.items():
                cookie_dict = {
                    'name': key,
                    'value': value}
                self.driver.add_cookie(cookie_dict)
            self.driver.get(url="{0}/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=10"
                                "&appmsgid={1}&isMul=1&token={2}&lang=zh_CN".format(self.url, appmsgid, self.token))
            ActionChains(self.driver).move_to_element(
                self.driver.find_element_by_xpath('//*[@id="js_add_appmsg"]')).perform()
            try:
                WebDriverWait(self.driver, 60).until(
                    EC.element_to_be_clickable((By.LINK_TEXT, "写新图文"))
                )
                self.driver.find_element_by_link_text("写新图文").click()
            except Exception as e:
                print(e)
            WebDriverWait(self.driver, 60).until(
                EC.element_to_be_clickable((By.XPATH, '//*[@id="title"]'))
            )
            self.driver.find_element_by_xpath('//*[@id="title"]').clear()
            self.driver.find_element_by_xpath('//*[@id="title"]').send_keys(1)
            time.sleep(0.5)
            self.driver.find_element_by_xpath('//*[@id="js_submit"]/button').click()
            time.sleep(2)
            self.driver.quit()
        except Exception as e:
            print(e)

    def material_management_spider_info(self):
        resp = self.session.get(
            '{0}/cgi-bin/settingpage?t=setting/index&action=index&token={1}&lang=zh_CN'
            '&f=json&ajax=1&random={2}'.format(self.url, self.token, random.random()))
        self.gh_nickname = ''
        try:
            data_infos = resp.json()
            self.gh_nickname = data_infos['setting_info']['nickname']['nickname']
        except:
            self.debug_log(resp.content)
        response = self.session.get('{}/cgi-bin/appmsg?begin=0&count=10&type=10&action=list_card'
                                    '&token={}&lang=zh_CN&f=json&ajax=1'.format(self.url, self.token), verify=False)
        try:
            data = response.json()
            appmsgid = data["app_msg_info"]["item"][0]["app_id"]
            result = self.session.get(
                "{0}/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=10"
                "&appmsgid={1}&isMul=1&token={2}&lang=zh_CN&f=json&ajax=1".format(
                    self.url, appmsgid, self.token), verify=False
            )
            try:
                data_info = json.loads(result.json()["app_msg_info"])
                if len(data_info["item"][0]["multi_item"]) == 1:
                    state = "未修改成功"
                elif len(data_info["item"][0]["multi_item"]) == 2:
                    state = "修改成功"
                else:
                    state = "修改异常"
                info = {
                    "gh_id": self.gh_id,
                    "nickname": self.gh_nickname,
                    "state": state
                }
                with open("account_material_management.json", "a", encoding="utf-8") as f:
                    f.write(json.dumps(info)+"\r")
            except (UnicodeError, AttributeError, KeyError, ValueError, IndexError):
                self.debug_log(result.content)
        except (KeyError, IndexError, ValueError, AttributeError):
            self.debug_log(response.content)


class ReportGenerator:
    def __init__(self, library, date_to_report):
        """
        :param utils.AccountLibrary library:
        :param date_to_report:
        """
        self.date = date_to_report
        self.library = library
        self.gh_id = None

    def save_excel(self, workbook, name):
        filename = '{} {}.xlsx'.format(self.date, name)
        try:
            workbook.save(filename)
            workbook.close()
        except PermissionError:
            print('无法写入{}，请检查是否在Excel中打开了文件，如有需要请另存为并关闭'.format(filename))

    def date_info(self):
        workbook, sheet = utils.make_workbook()
        set_columns_width(sheet, [20, 20, 20, 15])
        sheet.append(['名称', '原始ID',  '素材修改状态'])
        row_index = 1
        print("开始生成表格")
        f = open("account_material_management.json", "r", encoding='utf-8')
        for lines in f.readlines():
            dic = json.loads(lines)
            row_index += 1
            list1 = [dic["nickname"], dic["gh_id"], dic["state"]]
            sheet.append(list1)
        set_styles(sheet['A1:C1'], fill_main, align_header)
        set_border(sheet['A1:C{}'.format(row_index)])
        self.save_excel(workbook, '账号素材修改')


class EditorThread(threading.Thread):
    def __init__(self, service, task):
        threading.Thread.__init__(self)
        self.service = service
        self.task = task

    def run(self):
        c = WeChatInfrastructureEditor(srv)
        try:
            cookie = c.enter(self.task['gh_id'])
            if not cookie:
                return
            c.material_management_info(cookie)
            c.material_management_spider_info()
        except ConnectionError:
            pass


if __name__ == '__main__':
    m = tasks.default_manager()
    srv = use_default_login()
    chunks = m.get_task_chunks(5)
    total_chunks = len(chunks)
    current_chunk = 1
    for chunk in chunks:
        print('=====第{}批线程开始====='.format(current_chunk))
        pool = []
        for task_item in chunk:
            thread = EditorThread(srv, task_item)
            thread.start()
            pool.append(thread)
        for thread in pool:
            thread.join()
        print('=====第{}/{}批线程结束====='.format(current_chunk, total_chunks))
        current_chunk += 1
    ret = ReportGenerator(
        tasks.default_manager(), utils.get_today())
    ret.date_info()
    os.remove("account_material_management.json")
    input('运行完毕，按回车键(Enter)退出')
